const _ = require('lodash');
const nodemailer = require('nodemailer');
const ReportData = require('../../lib/ReportData');
const fs = require('fs');
module.exports = app => {
  const {router, middleware} = app;
  const prefix = '/api/report';

  let reportData = new ReportData(app);

  /**
   * 预览邮件内容
   */
  router.post(prefix + '/:report_id/preview', middleware.api(2), async ctx => {
    ctx.body = await app.spiderReportData.renderHtml(ctx.params.report_id,
        ctx.request.body.appendContent || '无');
  });

  /**接收邮件额外的文件*/
  router.post(prefix + '/:report_id/upload_file', middleware.api(2),
      middleware.upload, async ctx => {
        let stream = ctx.stream, filename = Date.now();
        let report = await app.model.Report.findOne(
            {where: {id: ctx.params.report_id}});
        if (!report)
          return ctx.helper.error('不存在的日志');
        let path = app.config.screenshot.path + '/' + filename;

        fs.createWriteStream(path);
        stream.pipe(fs.createWriteStream(path));
        let file = await app.model.File.create(
            {file: filename, name: stream.filename, selected: true});
        await report.addFiles(file);
        // app.model.ReportImage.create({file_id: file.id, report_id: report.id});
        ctx.body = file;
      });

  /**读取 日志 上传文件记录*/
  router.get(prefix + '/:report_id/files', async ctx => {
    let report = await app.model.Report.findOne({
      where: {id: ctx.params.report_id},
      include: [
        {
          model: app.model.File,
          as: 'files',
          required: false,
          where: {name: {[app.Sequelize.Op.ne]: null}},
        }],
    });
    if (!report)
      return this.helper.error('不存在的日志');
    ctx.body = report.files;
  });

  /**
   * 发送邮件
   */
  router.post(prefix + '/:report_id/send_email', middleware.api(2),
      async ctx => {
        let report_id = ctx.params.report_id;
        let appendContent = ctx.request.body.appendContent || '无';
        let bcc = _.compact(_.uniq(ctx.request.body.emails));

        if (_.isEmpty(bcc))
          return ctx.helper.error('没有收件人');
        let sender = nodemailer.createTransport(app.config.mail);
        let {subject, html, text} = await app.reportData.renderHtml(report_id,
            appendContent, false);
        await new Promise(resolve => {
          sender.sendMail(
              {from: app.config.mail.auth.user, bcc, subject, html, text},
              err => {
                resolve();
              });
        });
        ctx.body = '邮件发送成功';
      });
};